/**
 * 
 */
package dt.inlee.common.interceptor;

import java.io.PrintWriter;
import java.util.Collections;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import dt.inlee.common.constant.CommonConstant;
import dt.inlee.common.util.BaseUtil;
import dt.inlee.common.util.SystemResourceUtil;

/**
 * 功能说明：账号重复登录拦截器
 * 
 * @作者： 张可贵 创建日期： 2010-5-21
 */
public class ReLoginInterceptor extends AbstractInterceptor {
	/**
	 * 
	 */
	private static Logger log = Logger.getLogger(ReLoginInterceptor.class);
	private static final long serialVersionUID = -2884243662434423013L;
	// 设置用户姓名字段
	private String userNameField = "userName";

	public String getUserNameField() {
		return userNameField;
	}

	public void setUserNameField(String userNameField) {
		this.userNameField = userNameField;
	}

	/**
	 * 判断当前登录操作的session id 是否与在线用户列表中该用户的session id一致
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		log.debug("ReLoginInterceptor.intercept()");
		log.debug("userNameField:" + userNameField);
		String policy = SystemResourceUtil.getInstance().getResourceAsString("LOGIN_POLICY");
		if (BaseUtil.isEmpty(policy) || policy.trim().equalsIgnoreCase("kick_repeat"))
			return invocation.invoke();
		else {
			// 取得界面输入的用户名
			String userName = invocation.getStack().findString(userNameField);
			// 在线用户列表
			Map<String, String> onlineUser = Collections.emptyMap();
			ServletContext sc = ServletActionContext.getServletContext();
			onlineUser = (Map<String, String>) sc.getAttribute(CommonConstant.SERVLETCONTEXT_ONLINE_USER);
			// 如果取得用户列表为空，直接执行其他的拦截器
			if (onlineUser == null) {
				return invocation.invoke();
			}
			String sessionId = onlineUser.get(userName);
			log.debug("sessionId=" + sessionId);
			if (!BaseUtil.isEmpty(sessionId)) {
				String reLoginMessage = "<script type='text/javascript'>" + "jAlert('对不起该账号已经在其他地方登录!');"
						+ "location.href='" + sc.getContextPath() + "/page/exitLogin.action';" + "</script>";
				ServletActionContext.getResponse().setHeader("content-type", "text/html; charset=utf-8");
				PrintWriter out = ServletActionContext.getResponse().getWriter();
				// 页面上显示
				out.println(reLoginMessage);
				out.flush();
				out.close();
				return null;
			}
		}

		return invocation.invoke();
	}
}
